package com.aaa.sso.service;

import com.aaa.sso.feign.MenuFeign;
import com.aaa.sso.feign.UserFeign;
import com.aaa.entity.Menu;
import com.aaa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 根据登录用户的信息查询当前用户的权限以及库中加密过的密码
 * 后面会将登录用户的信息封存到token中
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MenuFeign menuFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户的手机号查找对应的用户
        User user = userFeign.getByUsername(username);
        if (user==null){
            throw new RuntimeException("账号不存在");
        }

        //如果用户存在，获取该用户对应的权限
        List<Menu> menuList = menuFeign.findByUserid(user.getUserId());

        Collection<SimpleGrantedAuthority> authorities = menuList.stream().map(item -> new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
        //这里的密码还需要进行加密
        return new org.springframework.security.core.userdetails.User(user.getPhone(),user.getPassword(),authorities);
    }
}
